import { history } from 'umi';
import { message } from 'antd';
import { parse } from 'qs';
import { login, logout, getFakeCaptcha } from '@/services/oauth';


export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

const Model = {
  namespace: 'oauth',
  state: {
  },
  effects: {

    *logout(_, { call ,put}) {
      const response = yield call(logout);
      message.success('登出成功！');
      localStorage.removeItem('access-token');
      localStorage.removeItem('enterpriseId');
      localStorage.removeItem('isLogin');
      yield put({
        type: 'removeLoginData',
        payload: response,
      });
      history.replace('/user/login');
    },
    *login({ payload }, { call, put }) {
      const response = yield call(login, payload);
      

      if (response.success) {
        yield put({
          type: 'setLoginData',
          payload: response,
        });
        localStorage.setItem('access-token', response.data.token);
        localStorage.setItem('isLogin',true);
        message.success('登录成功！');
        const urlParams = new URL(window.location.href);
        const params = getPageQuery();
        let { redirect } = params;
        console.log('redirect', redirect)
        if (redirect) {
          const redirectUrlParams = new URL(redirect);

          if (redirectUrlParams.origin === urlParams.origin) {
            redirect = redirect.substr(urlParams.origin.length);
            console.log('redirect', redirect)
            if (redirect.match(/^\/.*#/)) {
              redirect = redirect.substr(redirect.indexOf('#') + 1);
            }
          } else {
            window.location.href = redirect;
            return;
          }
        }
        history.replace(redirect || '/');
      }
    },

    *getCaptcha({ payload }, { call }) {
      yield call(getFakeCaptcha, payload);
    },
  },
  reducers: {
    setLoginData(state, { payload }) {
      return { ...state, 
        isLogin :true,
        loginData:payload.data
      };
    },
    removeLoginData(state, { payload }){
      return { ...state, 
        isLogin :false,
        loginData:{}
      };
    }
    
  },
};
export default Model;
